﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Flagwind.ComponentModel
{
	public static class HttpClientExtension
	{
		public static HttpResponseMessage PostForm(string url, IEnumerable<KeyValuePair<string, string>> paramts)
		{
			using(var client = new System.Net.Http.HttpClient())
			{
				client.Timeout = TimeSpan.FromMinutes(3);

				using(var content = new System.Net.Http.FormUrlEncodedContent(paramts))
				{
					try
					{
						//POST 请求
						var response = client.PostAsync(url, content);

						return response.Result;
					}
					catch(Exception ex)
					{
						content.Dispose();
						client.Dispose();

						throw ex;
					}
				}
			}
		}

		/// <summary>
		/// post请求
		/// </summary>
		/// <param name="url"></param>
		/// <param name="jsonStr">json字符串</param>
		/// <returns></returns>
		public static HttpResponseMessage Post(string url, string jsonStr)
		{
			using(var client = new System.Net.Http.HttpClient())
			{
				client.Timeout = TimeSpan.FromMinutes(3);

				using(var content = new StringContent(jsonStr, Encoding.UTF8))
				{
					content.Headers.ContentType.MediaType = "application/json";

					try
					{
						var response = client.PostAsync(url, content);

						return response.Result;
					}
					catch(Exception ex)
					{
						content.Dispose();
						client.Dispose();

						throw ex;
					}
				}
			}
		}

		/// <summary>
		/// post请求
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="url"></param>
		/// <param name="entity"></param>
		/// <returns></returns>
		public static HttpResponseMessage Post<T>(string url, T entity) where T : class, new()
		{
			string postData = Flagwind.Runtime.Serialization.Serializer.Json.Serialize(entity);

			using(var client = new System.Net.Http.HttpClient())
			{
				client.Timeout = TimeSpan.FromMinutes(3);

				using(var content = new StringContent(postData, Encoding.UTF8))
				{
					content.Headers.ContentType.MediaType = "application/json";

					try
					{
						var response = client.PostAsync(url, content);

						return response.Result;
					}
					catch(Exception ex)
					{
						content.Dispose();
						client.Dispose();

						throw ex;
					}
				}
			}
		}
	}
}
